import json
import os
from osgeo import gdal,ogr
from PIL import Image
from PIL import ImageDraw
import numpy as np
import cv2
from tqdm import tqdm


pid = os.getpid()
print("当前进程 ID 为:", pid)


def shp_clip_tif(shp_path,tif_path,save_dir):
    dataset = gdal.Open(tif_path)
    dataSource = ogr.Open(shp_path)
    layer = dataSource.GetLayer()
    for featrue in tqdm(layer):
        fid = featrue.GetFID()
        out_path = os.path.join(save_dir,f"{fid}.png")
        gdal.Warp(
            out_path, 
            dataset, 
            format='PNG', 
            # outputSRS=None,
            cutlineDSName=dataSource,
            cutlineLayer=layer.GetName(),
            cutlineWhere=f"fid={fid}",
            cropToCutline=True)
    del dataset
    dataSource.Destroy()
    return



def clip_image(image_path,json_path,save_dir):
    with open(json_path,'r',encoding='utf-8') as json_file:
        data = json.load(json_file)
        
    image = Image.open(image_path)
    mask = np.zeros_like(image)
    
    
    cropped_img = cv2.bitwise_and(image, mask)
    
    for i,obj in enumerate(data["shapes"]):
        polygon = obj['points']
        # mask = Image.new("L", image.size, 0)
        # draw = ImageDraw.Draw(mask)
        # draw.polygon(polygon, outline=1, fill=1)
        # cropped_image = Image.new('RGB', (200, 200))
        # draw = ImageDraw.Draw(cropped_image)
        # draw.polygon(pts, outline=1, fill=1)
        # result = image.transform((200, 200), Image.PERSPECTIVE, data=pts, resample=Image.BILINEAR)
        
        del draw
        
    return


if __name__ == "__main__":
    ''''''
    shp_path = r"/data/fengyy/dateset/202407/0006_0007_沧州市_shp/0006_0007_沧州市.shp"
    tif_path = r"/data/fengyy/dateset/202407/0006_0007_沧州市_shp/0006_0007_沧州市.tif"
    save_dir=r"/data/fengyy/dateset/202407/dapengtest"
    shp_clip_tif(shp_path,tif_path,save_dir)
    ''''''
    # image_path = r"/data/fengyy/dateset/core.245481/0000000(800_800)(400_400)0(J50E004020(1_0))20200710203147.jpg"
    # json_path = r"/data/fengyy/dateset/core.245481/0000000(800_800)(400_400)0(J50E004020(1_0))20200710203147.json"
    # save_dir=r"/data/fengyy/dateset/202407/dapengtest"
    # clip_image(image_path,json_path,save_dir)
    pass